﻿using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;
using CID.Execution.Agent.Service.Configuration;
using CID.Execution.Support;
using NailsFramework;

namespace CID.Execution.Agent.Service
{
    public partial class AgentWindowsService : ServiceBase
    {
        private IAgentCoordinator coordinator;
        private ServiceHost host;

        public AgentWindowsService()
        {
            InitializeComponent();

            coordinator = Nails.ObjectFactory.GetObject<IAgentCoordinator>();
        }

        protected override void OnStart(string[] args)
        {
            coordinator.Start();
            OpenHost();
        }

        protected override void OnStop()
        {
            CloseHost();
            coordinator.Stop();
        }

        private void OpenHost()
        {
            CloseHost();
            host = new ServiceHost(typeof(AgentServiceWCFWrapper), new Uri(UrlProvider.GetDeploymentAgentUrl(ApplicationConfiguration.AgentServiceHostingAddress)));
            host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
            host.Open();
        }

        private void CloseHost()
        {
            if (host != null)
            {
                host.Close();
                host = null;
            }
        }
    }
}
